<? 
require_once("xajax/xajax.inc.php");
$xajax = new xajax();

function imprime()
{
	//damos la vuelta al xml
	$xml = simplexml_load_file('log.xml');
	$xml2array = object2array($xml);
	$xml2arrayRev = array_reverse($xml2array['twit']);
	$newContent = '<form action="" id="borrarselec" id="name"><strong>Seleccionados:</strong> <input type="button" value="Borrar" onClick="xajax_borrar(xajax.getFormValues(borrarselec))">';
	$newContent .= '<table>';
	$total = count($xml2arrayRev);

	//mostramos los mensajes
	foreach ($xml2arrayRev as $twit) {
		$contador++;
		if (!$twit['blocked'])
			$tid = $total - $contador;
			$newContent .= '<tr><td>';
			$newContent .= '<input type="checkbox" name="selecc[]" value='.$tid.'>';
			$newContent .= ' <span class="from"><a href="?q=user/'.$twit['userid'].'">'.$twit['from'].'</a></span> '.$twit['body'].' <span class="date">'.$twit['date'];
	}
	$newContent .= '</table></form>';
	   
	// Instantiate the xajaxResponse object
	$objResponse = new xajaxResponse();

	// add a command to the response to assign the innerHTML attribute of
	// the element with id="SomeElementId" to whatever the new content is
	$objResponse->assign("tabmenu","innerHTML", $newContent);
	$objResponse->addScriptCall("xajax_muestra_bloqueados");

	//return the  xajaxResponse object
	return $objResponse;
}

function muestra_bloqueados()
{
	// do some stuff based on $arg like query data from a database and
	// put it into a variable like $newContent
	$xml = simplexml_load_file('blocked.xml');
	foreach ($xml->blocked as $banned) {
	   $newContent .= $banned->msisdn.'<br>';
	}
	   
	// Instantiate the xajaxResponse object
	$objResponse = new xajaxResponse();

	// add a command to the response to assign the innerHTML attribute of
	// the element with id="SomeElementId" to whatever the new content is
	$objResponse->assign("bloqueados","innerHTML", $newContent);

	//return the  xajaxResponse object
	return $objResponse;
}

function recuento($arg)
{
	// do some stuff based on $arg like query data from a database and
	// put it into a variable like $newContent
	$salida = 140 - strlen($arg['cuerpo']);
	if ($salida < 0) {
	$salida = '<font color="red">'.$salida.'</font>';
	}

	// Instantiate the xajaxResponse object
	$objResponse = new xajaxResponse();

	// add a command to the response to assign the innerHTML attribute of
	// the element with id="SomeElementId" to whatever the new content is
	$objResponse->assign("restante","innerHTML", $salida);

	//return the  xajaxResponse object
	return $objResponse;
}

function twittear($arg)
{
	// Validation
	$salida = "";
	if ($arg['cuerpo'] == "")
		$salida = "Necesitas escribir algo para poder hacer un update";

	if (strlen($arg['cuerpo']) > 140)
		$salida = "El update supera los 140 carácteres";

	if ($salida != "") {
		// Instantiate the xajaxResponse object
		$objResponse = new xajaxResponse();
		$objResponse->addAlert($salida);
	} else {

	// do some stuff based on $arg like query data from a database and
	// put it into a variable like $newContent
	$fecha = date('d-m-y H:i'); 
	$xml = simplexml_load_file('log.xml');
	$twit = $xml->addChild('twit');
	$twit->addChild('from', 'admin');
	$twit->addChild('msisdn', 'admin');
	$twit->addChild('body', $arg['cuerpo']);
	$twit->addChild('date', $fecha);
	$twit->addChild('userid', '1');
	$twit->addChild('blocked', 0);
	$xml->asXML('log.xml');

	// Twitter credentials
	$username = 'proelapi';
	$password = 'pepito';

	// The twitter API address
	$url = 'http://twitter.com/statuses/update.xml';

	$curl_handle = curl_init();
	curl_setopt($curl_handle, CURLOPT_URL, "$url");
	curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
	curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl_handle, CURLOPT_POST, 1);
	curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$arg[cuerpo]");
	curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");
	$buffer = curl_exec($curl_handle);
	curl_close($curl_handle);

	// Instantiate the xajaxResponse object
	$objResponse = new xajaxResponse();

	// add a command to the response to assign the innerHTML attribute of
	// the element with id="SomeElementId" to whatever the new content is
	$objResponse->assign("response","innerHTML", $salida);
	$objResponse->addScriptCall("xajax_imprime");
	}

	//return the  xajaxResponse object
	return $objResponse;
}

function bloquear($arg)
{
	// Validation
	$salida = "";
	if ($arg['msisdn'] == "")
		$salida = "Necesitas escribir el msisdn del usuario para bloquearlo";

	if (!ereg("([0-9])", $arg['msisdn']))
		$salida = "El msisdn no es válido";

	if ($salida != "") {
		// Instantiate the xajaxResponse object
		$objResponse = new xajaxResponse();
		$objResponse->addAlert($salida);
	} else {

	$xml = simplexml_load_file('blocked.xml');
	$blocked = $xml->addChild('blocked');
	$blocked->addChild('msisdn', $arg['msisdn']);
	$blocked->msisdn->addAttribute('blocked', '1');
	$xml->asXML('blocked.xml');

	// Instantiate the xajaxResponse object
	$objResponse = new xajaxResponse();

	// add a command to the response to assign the innerHTML attribute of
	// the element with id="SomeElementId" to whatever the new content is
	$objResponse->addScriptCall("xajax_muestra_bloqueados");
	}

	//return the  xajaxResponse object
	return $objResponse;
}

function desbloquear($arg)
{
	$xml = simplexml_load_file('blocked.xml');
	$xml->asXML('blocked.xml');

	// Instantiate the xajaxResponse object
	$objResponse = new xajaxResponse();
	$objResponse->addAlert($salida);

	// add a command to the response to assign the innerHTML attribute of
	// the element with id="SomeElementId" to whatever the new content is
//	$objResponse->addScriptCall("xajax_muestra_bloqueados");

	//return the  xajaxResponse object
	return $objResponse;
}

function borrar($arg)
{
	// do some stuff based on $arg like query data from a database and
	// put it into a variable like $newContent

        extract($arg);
	//validacion
	$objResponse = new xajaxResponse();

	if (!isset($selecc)) {
		$salida = "No has seleccionado ningún tweet";
		$objResponse->addAlert($salida);
	} else {
	
	$xml = simplexml_load_file('log.xml');
        foreach($selecc as $tid) {
		$xml->twit[$tid]->body = "lolo";
		}
	$xml->asXML('log.xml');	
	$objResponse->addScriptCall("xajax_imprime");
	}

	//return the  xajaxResponse object
	return $objResponse;
}

$xajax->registerFunction("imprime");
$xajax->registerFunction("muestra_bloqueados");
$xajax->registerFunction("recuento");
$xajax->registerFunction("twittear");
$xajax->registerFunction("bloquear");
$xajax->registerFunction("desbloquear");
$xajax->registerFunction("borrar");

$xajax->processRequest();

function object2array($object) {
    $return = NULL;
    if(is_array($object)) {
        foreach($object as $key => $value)
            $return[$key] = object2array($value);
    } else {
        $var = get_object_vars($object);
        if($var) {
            foreach($var as $key => $value)
                $return[$key] = ($key && !$value) ? NULL : object2array($value);
        } else return $object;
    }
    return $return;
}
?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Twitter open movilforum</title>
<link rel="stylesheet" type="text/css" href="style.css">
<?php $xajax->printJavascript(xajax); ?>
<script language="JavaScript" type="text/JavaScript">
function clearField(fieldId){
            var field = document.getElementById(fieldId);
            field.value = ""; }
function setField(fieldId, originalValue){
            var field = document.getElementById(fieldId);
            if(field.value == ""){
                        field.value = originalValue; } }
</script>
</head>

<body onLoad="xajax_imprime()">
<div id="header"><h3></h3></div>

<div id="content">
<div id="container">
	<span class="tit1">¿Que estás haciendo?</span>
	<div id="restante">140</div>

	<form id="mensaje">
		<textarea name="cuerpo" cols="40" rows="2"  onkeyup="xajax_recuento(xajax.getFormValues('mensaje'))"></textarea>
		<p class="submit"><input type="button" value="update" onClick="xajax_twittear(xajax.getFormValues('mensaje'))"></p>
	</form>

	<div id="tabmenu"></div>
</div>
</div>

<div id="admin">
	<b>Bloqueados</b> 
	<hr size=1 color=#00e000>
	<form id="bloquearform">
		<input type="text" id="msisdn" name="msisdn" value="Msisdn" size="12" onFocus="clearField('msisdn')" onBlur="setField('msisdn', 'Msisdn')"/>
		<input type="button" title="Bloquear" value = "block" onClick="xajax_bloquear(xajax.getFormValues('bloquearform'))">
	</form>
	<div id="bloqueados"></div>
</div>
	
</body>
</html>
